using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web.UI.WebControls;
using System.Xml.Linq;
using Code5Systems.FormMaster.Business;
using DotNetNuke.Services.Localization;

namespace Code5Systems.FormMaster
{

	public partial class FormMasterEdit : DotNetNuke.Entities.Modules.PortalModuleBase
	{
		
#region Helper Methods
		
		//Get the Name (label) given the ID for the control from the XmlDocument (used in the ascx page)
		public string GetControlName(string controlId)
		{
			return this.objFormCtl.GetControlNameById(this.xDoc, controlId);
		}
		
		//Return a FormControlInfo Object for the cell given the row and column in the table
		private XElement GetFormControlNode(string row, string col)
		{
			//Dim oNode As XmlNode
			
			//oNode = Me.objFormXmlDoc.SelectSingleNode("//Controls/Control[@TableRow=" & row & "][@TableCol=" & col & "]")
			
			//Return oNode
			
			return this.objFormCtl.GetControlElement(this.xDoc, row, col);
			
		}
		
		//Return a FormControlInfo Object for the cell given the row and column in the table
		private Code5Systems.FormMaster.Business.FormControlInfo GetFormControlInfo(string row, string col)
		{
			Code5Systems.FormMaster.Business.FormControlInfo objFormControlInfo = default(Code5Systems.FormMaster.Business.FormControlInfo);
			
			objFormControlInfo = this.objFormCtl.GetFormControlInfo(this.objFormInfo, row, col);
			
			return objFormControlInfo;
			
		}
		
		private void SaveFormDefinition()
		{
			Code5Systems.FormMaster.Business.FormPageController pageCtlr = new Code5Systems.FormMaster.Business.FormPageController();
			//pageCtlr.UpdateFormPage(GetCurrentPage())
			objFormInfo.CurrentPage.PageData = this.xDoc.ToString();
			pageCtlr.UpdateFormPage(objFormInfo.CurrentPage);
			
			//objFormCtl.UpdateFormDefinition(ModuleId, Me.xDoc.ToString(), Me.UserId)
			//Me.objFormInfo.FormDefinition = Me.xDoc.ToString()
		}
		
		//Set the Flags Bit Fields based on the Control Type.
		//The resulting value is later used with the BiteWise AND to determine
		//If a Design Input Control will be visible or not.
		private void SetFields(Code5Systems.FormMaster.Business.FormControlInfo objFormControlInfo)
		{
			
			switch (objFormControlInfo.Type)
			{
				case Code5Systems.FormMaster.Business.ControlType.CheckBox:
					editFields = (Code5Systems.FormMaster.Business.FormController.Fields) (editFields | Code5Systems.FormMaster.Business.FormController.Fields.Checked);
					editFields = (Code5Systems.FormMaster.Business.FormController.Fields) (editFields | Code5Systems.FormMaster.Business.FormController.Fields.AutoFillField);
					editFields = (Code5Systems.FormMaster.Business.FormController.Fields) (editFields | Code5Systems.FormMaster.Business.FormController.Fields.SendValueBy);
					break;
					
				case Code5Systems.FormMaster.Business.ControlType.CheckBoxList:
					editFields = (Code5Systems.FormMaster.Business.FormController.Fields) (editFields | Code5Systems.FormMaster.Business.FormController.Fields.ListItems);
					editFields = (Code5Systems.FormMaster.Business.FormController.Fields) (editFields | Code5Systems.FormMaster.Business.FormController.Fields.RepeatColumns);
					editFields = (Code5Systems.FormMaster.Business.FormController.Fields) (editFields | Code5Systems.FormMaster.Business.FormController.Fields.RepeatDirection);
					editFields = (Code5Systems.FormMaster.Business.FormController.Fields) (editFields | Code5Systems.FormMaster.Business.FormController.Fields.AutoFillField);
					editFields = (Code5Systems.FormMaster.Business.FormController.Fields) (editFields | Code5Systems.FormMaster.Business.FormController.Fields.SendValueBy);
					editFields = (Code5Systems.FormMaster.Business.FormController.Fields) (editFields | Code5Systems.FormMaster.Business.FormController.Fields.FillListItem);
					editFields = (Code5Systems.FormMaster.Business.FormController.Fields) (editFields | Code5Systems.FormMaster.Business.FormController.Fields.FieldQuery);
					editFields = (Code5Systems.FormMaster.Business.FormController.Fields) (editFields | Code5Systems.FormMaster.Business.FormController.Fields.Validators);
					break;
					
				case Code5Systems.FormMaster.Business.ControlType.DropDownList:
				case Code5Systems.FormMaster.Business.ControlType.ListBox:
					editFields = (Code5Systems.FormMaster.Business.FormController.Fields) (editFields | Code5Systems.FormMaster.Business.FormController.Fields.ListItems);
					editFields = (Code5Systems.FormMaster.Business.FormController.Fields) (editFields | Code5Systems.FormMaster.Business.FormController.Fields.Validators);
					editFields = (Code5Systems.FormMaster.Business.FormController.Fields) (editFields | Code5Systems.FormMaster.Business.FormController.Fields.AutoFillField);
					editFields = (Code5Systems.FormMaster.Business.FormController.Fields) (editFields | Code5Systems.FormMaster.Business.FormController.Fields.SendValueBy);
					editFields = (Code5Systems.FormMaster.Business.FormController.Fields) (editFields | Code5Systems.FormMaster.Business.FormController.Fields.FillListItem);
					editFields = (Code5Systems.FormMaster.Business.FormController.Fields) (editFields | Code5Systems.FormMaster.Business.FormController.Fields.FieldQuery);
					break;
					
				case Code5Systems.FormMaster.Business.ControlType.RadioButtonList:
					editFields = (Code5Systems.FormMaster.Business.FormController.Fields) (editFields | Code5Systems.FormMaster.Business.FormController.Fields.ListItems);
					editFields = (Code5Systems.FormMaster.Business.FormController.Fields) (editFields | Code5Systems.FormMaster.Business.FormController.Fields.RepeatColumns);
					editFields = (Code5Systems.FormMaster.Business.FormController.Fields) (editFields | Code5Systems.FormMaster.Business.FormController.Fields.RepeatDirection);
					editFields = (Code5Systems.FormMaster.Business.FormController.Fields) (editFields | Code5Systems.FormMaster.Business.FormController.Fields.Validators);
					editFields = (Code5Systems.FormMaster.Business.FormController.Fields) (editFields | Code5Systems.FormMaster.Business.FormController.Fields.AutoFillField);
					editFields = (Code5Systems.FormMaster.Business.FormController.Fields) (editFields | Code5Systems.FormMaster.Business.FormController.Fields.SendValueBy);
					editFields = (Code5Systems.FormMaster.Business.FormController.Fields) (editFields | Code5Systems.FormMaster.Business.FormController.Fields.FillListItem);
					editFields = (Code5Systems.FormMaster.Business.FormController.Fields) (editFields | Code5Systems.FormMaster.Business.FormController.Fields.FieldQuery);
					break;
					
				case Code5Systems.FormMaster.Business.ControlType.RegularExpressionValidator:
					editFields = (Code5Systems.FormMaster.Business.FormController.Fields) (editFields | Code5Systems.FormMaster.Business.FormController.Fields.RegEx);
					break;
					
				case Code5Systems.FormMaster.Business.ControlType.RequiredFieldValidator:
					editFields = (Code5Systems.FormMaster.Business.FormController.Fields) (editFields | Code5Systems.FormMaster.Business.FormController.Fields.InitialValue);
					break;
					
				case Code5Systems.FormMaster.Business.ControlType.TextBox:
					editFields = (Code5Systems.FormMaster.Business.FormController.Fields) (editFields | Code5Systems.FormMaster.Business.FormController.Fields.TextBox);
					editFields = (Code5Systems.FormMaster.Business.FormController.Fields) (editFields | Code5Systems.FormMaster.Business.FormController.Fields.TextMode);
					editFields = (Code5Systems.FormMaster.Business.FormController.Fields) (editFields | Code5Systems.FormMaster.Business.FormController.Fields.Columns);
					editFields = (Code5Systems.FormMaster.Business.FormController.Fields) (editFields | Code5Systems.FormMaster.Business.FormController.Fields.MaxLength);
					editFields = (Code5Systems.FormMaster.Business.FormController.Fields) (editFields | Code5Systems.FormMaster.Business.FormController.Fields.Validators);
					editFields = (Code5Systems.FormMaster.Business.FormController.Fields) (editFields | Code5Systems.FormMaster.Business.FormController.Fields.AutoFillField);
					editFields = (Code5Systems.FormMaster.Business.FormController.Fields) (editFields | Code5Systems.FormMaster.Business.FormController.Fields.SendValueBy);
					editFields = (Code5Systems.FormMaster.Business.FormController.Fields) (editFields | Code5Systems.FormMaster.Business.FormController.Fields.FieldQuery);
					
					if (objFormControlInfo.TextMode == TextBoxMode.MultiLine)
					{
						editFields = (Code5Systems.FormMaster.Business.FormController.Fields) (editFields | Code5Systems.FormMaster.Business.FormController.Fields.Rows);
					}
					break;
					
				case Code5Systems.FormMaster.Business.ControlType.HiddenField:
					editFields = (Code5Systems.FormMaster.Business.FormController.Fields) (editFields | Code5Systems.FormMaster.Business.FormController.Fields.AutoFillField);
					editFields = (Code5Systems.FormMaster.Business.FormController.Fields) (editFields | Code5Systems.FormMaster.Business.FormController.Fields.SendValueBy);
					editFields = (Code5Systems.FormMaster.Business.FormController.Fields) (editFields | Code5Systems.FormMaster.Business.FormController.Fields.FieldQuery);
					break;
					
				case Code5Systems.FormMaster.Business.ControlType.Label:
					editFields = (Code5Systems.FormMaster.Business.FormController.Fields) (editFields | Code5Systems.FormMaster.Business.FormController.Fields.HtmlEditor);
					break;
					
				case Code5Systems.FormMaster.Business.ControlType.FileUpload:
					editFields = (Code5Systems.FormMaster.Business.FormController.Fields) (editFields | Code5Systems.FormMaster.Business.FormController.Fields.FileUpload);
					editFields = (Code5Systems.FormMaster.Business.FormController.Fields) (editFields | Code5Systems.FormMaster.Business.FormController.Fields.Validators);
					break;
					
				case Code5Systems.FormMaster.Business.ControlType.SubmitButton:
					editFields = (Code5Systems.FormMaster.Business.FormController.Fields) (editFields | Code5Systems.FormMaster.Business.FormController.Fields.SubmitButton);
					break;
			}
			
			if (objFormControlInfo.Validators.Count > 0)
			{
				Code5Systems.FormMaster.Business.FormControlInfo objValidatorControlInfo = default(Code5Systems.FormMaster.Business.FormControlInfo);
				System.Collections.IEnumerator myEnumerator = objFormControlInfo.Validators.GetEnumerator();
				while (myEnumerator.MoveNext())
				{
					objValidatorControlInfo = (Code5Systems.FormMaster.Business.FormControlInfo) myEnumerator.Current;
					SetFields(objValidatorControlInfo);
				}
			}
			
		}
		
		private bool IsCellEmpty(int row, int col)
		{
			bool bIsEmpty = true;
			//Dim oControlNode As XmlNode
			XElement xControl = default(XElement);
			
			//oControlNode = objFormXmlDoc.SelectSingleNode("//Controls/Control[@TableRow=" & row & "][@TableCol=" & col & "]")
			xControl = this.objFormCtl.GetControlElement(this.xDoc, (row).ToString(), (col).ToString());
			if (xControl != null)
			{
				bIsEmpty = false;
			}
			
			return bIsEmpty;
			
		}
		
		//Do not let the user reduce the number of columns or rows while there are form controls
		//occupying the cells or controls with RowSpan and/or ColSpan attritues extending past the
		//specified Rows and Columns
		private bool ValidateTable(Code5Systems.FormMaster.Business.FormInfo objFormInfo)
		{
			bool bRetVal = true;
			int iRow = 0;
			int iCol = 0;
			int iRowSpan = 0;
			int iColSpan = 0;
			System.Collections.Generic.IEnumerable<XElement> xControls = default(System.Collections.Generic.IEnumerable<XElement>);
			
			XDocument xPageDoc = XDocument.Parse(objFormInfo.CurrentPage.PageData);
			
			xControls = from c in xPageDoc.Root.Elements("Controls").Elements("Control") where System.Convert.ToInt32(c.Attributes("TableCol").First().Value) > objFormInfo.CurrentPage.TableColumns || System.Convert.ToInt32(c.Attributes("TableRow").First().Value) > objFormInfo.CurrentPage.TableRows select c;
			
			if (xControls.Count() > 0)
			{
				bRetVal = false;
				DotNetNuke.UI.Skins.Skin.AddModuleMessage(this.LoaderCtl, Localization.GetString("InvalidTableOperation", this.LocalResourceFile), DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.YellowWarning);
			}
			
			//Now check if a Control has a RowSpan setting combined with the Row position which
			//when added together will extend past the specified Rows
			if (bRetVal)
			{
				//strXpath = "//Control[@RowSpan > 1]"
				//oControlNodes = objFormXmlDoc.SelectNodes(strXpath)
				
				xControls = from c in xDoc.Elements("Controls").Elements("Control") where System.Convert.ToInt32(c.Attributes("RowSpan").First().Value) > 1 select c;
				
				foreach (XElement xElem in xControls)
				{
					iRow = 0;
					iRowSpan = 0;
					if (xElem.AttributeExists("TableRow"))
					{
						iRow = System.Convert.ToInt32(xElem.Attributes("TableRow").First().Value);
					}
					
					if (xElem.AttributeExists("RowSpan"))
					{
						iRowSpan = System.Convert.ToInt32(xElem.Attributes("RowSpan").First().Value);
					}
					if (iRow + iRowSpan - 1 > objFormInfo.CurrentPage.TableRows)
					{
						bRetVal = false;
						DotNetNuke.UI.Skins.Skin.AddModuleMessage(this.LoaderCtl, Localization.GetString("InvalidRowSpanOperation", this.LocalResourceFile), DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.YellowWarning);
					}
				}
			}
			
			//Now check if a Control has a ColSpan setting combined with the Column position which
			//when added together will extend past the specified Columns
			if (bRetVal)
			{
				//strXpath = "//Control[@ColSpan > 1]"
				//oControlNodes = objFormXmlDoc.SelectNodes(strXpath)
				
				xControls = from c in xDoc.Elements("Controls").Elements("Control") where System.Convert.ToInt32(c.Attributes("ColSpan").First().Value) > 1 select c;
				
				foreach (XElement xElem in xControls)
				{
					iCol = 0;
					iColSpan = 0;
					if (xElem.AttributeExists("TableCol"))
					{
						iCol = System.Convert.ToInt32(xElem.Attributes("TableCol").First().Value);
					}
					
					if (xElem.AttributeExists("ColSpan"))
					{
						iColSpan = System.Convert.ToInt32(xElem.Attributes("ColSpan").First().Value);
					}
					
					if (iCol + iColSpan - 1 > objFormInfo.CurrentPage.TableColumns)
					{
						bRetVal = false;
						DotNetNuke.UI.Skins.Skin.AddModuleMessage(this.LoaderCtl, Localization.GetString("InvalidColSpanOperation", this.LocalResourceFile), DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.YellowWarning);
					}
				}
			}
			
			return bRetVal;
			
		}
		
		//A dropdown list cannot have more than 1 selected ListItem
		//The selCount param is used when changing a control to a Dropdown
		//we must make sure there is only one Selected ListItem so the count can be 1
		private bool ValidateDropdownList(Code5Systems.FormMaster.Business.FormControlInfo objFormControlInfo, int selCount = 0)
		{
			bool bRetVal = false;
			System.Collections.Generic.IEnumerable<XElement> xSelected = default(System.Collections.Generic.IEnumerable<XElement>);
			XElement xControl = default(XElement);
			
			xControl = objFormCtl.GetControlElement(this.xDoc, objFormControlInfo.ID);
			if (xControl != null)
			{
				bRetVal = true;
				xSelected = from e in xControl.Elements("ListItems").Elements("ListItem") where System.Convert.ToBoolean(e.Attributes("Selected").First().Value) == true select e;
				if (xSelected.Count() > selCount)
				{
					bRetVal = false;
					DotNetNuke.UI.Skins.Skin.AddModuleMessage(this.LoaderCtl, Localization.GetString("InvalidDropdownOperation", this.LocalResourceFile), DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.YellowWarning);
				}
			}
			return bRetVal;
			
		}
		
		//Move ListItems Up or Down
		private bool ChangeListItemPosition(bool moveUp, int index)
		{
			bool bRetVal = true;
			XElement xControl = default(XElement);
			System.Collections.Generic.IEnumerable<XElement> xListItems = default(System.Collections.Generic.IEnumerable<XElement>);
			XElement xSource = default(XElement);
			XElement xTarget = null;
			
			if (!(ViewState["ControlLocation"] == null))
			{
				xControl = GetFormControlNode((oCtlLoc.Row).ToString(), (oCtlLoc.Col).ToString());
				
				if (xControl != null)
				{
					
					xListItems = xControl.Elements("ListItems").Elements("ListItem");
					
					if (xListItems.Count() > 1)
					{
						xSource = xListItems.ElementAt(index);
						
						if (moveUp)
						{
							if (index > 0)
							{
								xTarget = xListItems.ElementAt(index - 1);
							}
							else
							{
								bRetVal = false;
							}
						}
						else
						{
							if (index < xListItems.Count() - 1)
							{
								xTarget = xListItems.ElementAt(index + 1);
							}
							else
							{
								bRetVal = false;
							}
						}
						
						if ((xSource != null) && (xTarget != null))
						{
							//// Category is a hold over from early Form Master. 
							//// We don't use it any more.
							//string srcCategory = String.Empty;
							//if (xSource.Attributes("Category").FirstOrDefault() != null)
							//{
							//	srcCategory = xSource.Attributes("Category").First().Value;
							//	xSource.Attributes("Category").First().Value = xTarget.Attributes("Category").First().Value;
							//	xTarget.Attributes("Category").First().Value = srcCategory;
							//}

							string srcText = (string) (xSource.Attributes("Text").First().Value);
							string srcValue = (string) (xSource.Attributes("Value").First().Value);
							string srcSelected = (string) (xSource.Attributes("Selected").First().Value);
							xSource.Attributes("Text").First().Value = xTarget.Attributes("Text").First().Value;
							xSource.Attributes("Value").First().Value = xTarget.Attributes("Value").First().Value;
							xSource.Attributes("Selected").First().Value = xTarget.Attributes("Selected").First().Value;
							xTarget.Attributes("Text").First().Value = srcText;
							xTarget.Attributes("Value").First().Value = srcValue;
							xTarget.Attributes("Selected").First().Value = srcSelected;
						}
					}
				}
			}
			
			return bRetVal;
			
		}
		
		//Fills a FormControlInfo Class with data from the Posted Control Input form
		private void FillFormControlInfo(Code5Systems.FormMaster.Business.FormControlInfo objFormControlInfo)
		{
			
			objFormControlInfo.Type = int.Parse(this.lstType.SelectedValue).ToEnum<ControlType>();
			objFormControlInfo.Enabled = !this.chkControlDisabled.Checked;
			objFormControlInfo.Label = this.txtLabel.Text;
			objFormControlInfo.FieldName = this.txtFieldName.Text;
			objFormControlInfo.LabelCssClass = this.txtLabelCssClass.Text;
			objFormControlInfo.CssClass = this.txtCssClass.Text;
			objFormControlInfo.HideLabel = this.chkHideLabel.Checked;
			objFormControlInfo.Width = this.txtWidth.Text;
			objFormControlInfo.Height = this.txtHeight.Text;
			objFormControlInfo.ConnectionString = this.txtConnection.Text;
			objFormControlInfo.FieldQuery = this.txtFieldQuery.Text;
			objFormControlInfo.CascadingFieldQuery = this.txtCascadingFieldQuery.Text;
			objFormControlInfo.FillListItemText = this.txtFillListItemText.Text;
			objFormControlInfo.FillListItemValue = this.txtFillListItemValue.Text;
			objFormControlInfo.AttachFile = this.chkAttachFile.Checked;
			objFormControlInfo.ExcludeLink = this.chkExcludeLink.Checked;
			objFormControlInfo.ARToken = this.txtARToken.Text;
			objFormControlInfo.ExcludeField = this.chkExcludeField.Checked;
			objFormControlInfo.WrapHard = this.chkWrapHard.Checked;
			objFormControlInfo.UseCalendar = this.chkUseCalendar.Checked;
			objFormControlInfo.AllowMarkup = this.chkAllowMarkup.Checked;
			objFormControlInfo.EncryptField = this.chkEncryptField.Checked;
			objFormControlInfo.ShowOnOwnRow = this.chkShowOnOwnRow.Checked;
			objFormControlInfo.Formula = this.txtFormula.Text;
			
			objFormControlInfo.CascadingList = this.chkCascadingList.Checked;
			if (objFormControlInfo.CascadingList)
			{
				objFormControlInfo.ParentControlID = this.lstCascadeParent.SelectedValue;
				objFormControlInfo.PromptText = this.txtPromptText.Text;
				objFormControlInfo.NotFoundText = this.txtNotFoundText.Text;
				objFormControlInfo.SelectText = this.txtSelectText.Text;
				objFormControlInfo.IsChildList = true;
				
				Code5Systems.FormMaster.Business.FormControlInfo parent = this.objFormCtl.GetFormControlInfo(objFormControlInfo.ParentControlID);
				if (parent != null)
				{
					parent.IsParentList = true;
					parent.ChildControlName = objFormControlInfo.FieldName;
					parent.ChildControlID = objFormControlInfo.ID;
					this.objFormCtl.UpdateControlValues(this.xDoc, parent);
					this.objFormCtl.FormInfo.CurrentPage.PageData = this.xDoc.ToString();
				}
			}
			else
			{
				// If this field was a child we must clear the parent
				if (objFormControlInfo.IsChildList)
				{
					Code5Systems.FormMaster.Business.FormControlInfo parent = this.objFormCtl.GetFormControlInfo(objFormControlInfo.ParentControlID);
					if (parent != null)
					{
						parent.IsParentList = false;
						parent.ChildControlName = string.Empty;
						parent.ChildControlID = string.Empty;
						this.objFormCtl.UpdateControlValues(this.xDoc, parent);
					}
				}
				objFormControlInfo.ParentControlID = string.Empty;
				if (!objFormControlInfo.IsParentList)
				{
					objFormControlInfo.ChildControlID = string.Empty;
				}
				//objFormControlInfo.PromptText = String.Empty
				//objFormControlInfo.NotFoundText = String.Empty
				//objFormControlInfo.SelectText = String.Empty
				objFormControlInfo.IsChildList = false;
			}
			
			
			switch (this.lstAutoFillType.SelectedValue)
			{
				case "0":
					objFormControlInfo.AutoFillType = Code5Systems.FormMaster.Business.FormController.AutoFillType.None;
					break;
				case "1":
					objFormControlInfo.AutoFillType = Code5Systems.FormMaster.Business.FormController.AutoFillType.Membership;
					objFormControlInfo.AutoFillFrom = this.lstAutoFillFieldFrom.SelectedValue;
					break;
				case "2":
					objFormControlInfo.AutoFillType = Code5Systems.FormMaster.Business.FormController.AutoFillType.Session;
					objFormControlInfo.AutoFillFrom = this.txtAutoFillFieldParam.Text;
					break;
				case "3":
					objFormControlInfo.AutoFillType = Code5Systems.FormMaster.Business.FormController.AutoFillType.Url;
					objFormControlInfo.AutoFillFrom = this.txtAutoFillFieldParam.Text;
					break;
				case "4":
					objFormControlInfo.AutoFillType = Code5Systems.FormMaster.Business.FormController.AutoFillType.Cookie;
					objFormControlInfo.AutoFillFrom = this.txtAutoFillFieldParam.Text;
					break;
				case "5":
					objFormControlInfo.AutoFillType = Code5Systems.FormMaster.Business.FormController.AutoFillType.FormQuery;
					objFormControlInfo.AutoFillFrom = this.txtAutoFillFieldParam.Text;
					objFormControlInfo.FillListItemText = this.txtFillListItemText.Text;
					objFormControlInfo.FillListItemValue = this.txtFillListItemValue.Text;
					break;
				case "6":
					objFormControlInfo.AutoFillType = Code5Systems.FormMaster.Business.FormController.AutoFillType.FieldQuery;
					objFormControlInfo.AutoFillFrom = this.txtAutoFillFieldParam.Text;
					objFormControlInfo.FillListItemText = this.txtFillListItemText.Text;
					objFormControlInfo.FillListItemValue = this.txtFillListItemValue.Text;
					break;
				case "7":
					objFormControlInfo.AutoFillType = Code5Systems.FormMaster.Business.FormController.AutoFillType.ServerVariables;
					objFormControlInfo.AutoFillFrom = this.lstServerVariables.SelectedValue;
					break;
			}
			
			switch (this.lstSendValueBy.SelectedValue)
			{
				case "0":
					objFormControlInfo.SendValueBy = Code5Systems.FormMaster.Business.FormController.SendValueBy.None;
					break;
				case "1":
					objFormControlInfo.SendValueBy = Code5Systems.FormMaster.Business.FormController.SendValueBy.Session;
					objFormControlInfo.SendValueByName = this.txtSendValueByName.Text;
					break;
				case "2":
					objFormControlInfo.SendValueBy = Code5Systems.FormMaster.Business.FormController.SendValueBy.Url;
					objFormControlInfo.SendValueByName = this.txtSendValueByName.Text;
					break;
				case "3":
					objFormControlInfo.SendValueBy = Code5Systems.FormMaster.Business.FormController.SendValueBy.Cookie;
					objFormControlInfo.CookieExpires = int.Parse(this.txtCookieExpires.Text);
					objFormControlInfo.SendValueByName = this.txtSendValueByName.Text;
					break;
				case "4":
					objFormControlInfo.SendValueBy = Code5Systems.FormMaster.Business.FormController.SendValueBy.Post;
					objFormControlInfo.SendValueByName = this.txtSendValueByName.Text;
					break;
					
				case "5":
					objFormControlInfo.SendValueBy = Code5Systems.FormMaster.Business.FormController.SendValueBy.PostAndSession;
					objFormControlInfo.SendValueByName = this.txtSendValueByName.Text;
					break;
					
				case "6":
					objFormControlInfo.SendValueBy = Code5Systems.FormMaster.Business.FormController.SendValueBy.PostAndCookie;
					objFormControlInfo.SendValueByName = this.txtSendValueByName.Text;
					objFormControlInfo.CookieExpires = int.Parse(this.txtCookieExpires.Text);
					break;
			}
			
			switch (this.lstLabelAlign.SelectedValue)
			{
				case "0":
					objFormControlInfo.LabelAlign = HorizontalAlign.NotSet;
					break;
				case "1":
					objFormControlInfo.LabelAlign = HorizontalAlign.Left;
					break;
				case "2":
					objFormControlInfo.LabelAlign = HorizontalAlign.Center;
					break;
				case "3":
					objFormControlInfo.LabelAlign = HorizontalAlign.Right;
					break;
			}
			
			switch (this.lstControlAlign.SelectedValue)
			{
				case "0":
					objFormControlInfo.ControlAlign = HorizontalAlign.NotSet;
					break;
				case "1":
					objFormControlInfo.ControlAlign = HorizontalAlign.Left;
					break;
				case "2":
					objFormControlInfo.ControlAlign = HorizontalAlign.Center;
					break;
				case "3":
					objFormControlInfo.ControlAlign = HorizontalAlign.Right;
					break;
			}
			
			switch (this.lstListItemToSave.SelectedValue)
			{
				case "0":
					objFormControlInfo.ListItemToSave = Code5Systems.FormMaster.Business.FormController.ListItemToSave.Text;
					break;
				case "1":
					objFormControlInfo.ListItemToSave = Code5Systems.FormMaster.Business.FormController.ListItemToSave.Value;
					break;
			}
			
			
			switch (objFormControlInfo.Type)
			{
				case Code5Systems.FormMaster.Business.ControlType.CheckBox:
					objFormControlInfo.Checked = this.chkChecked.Checked;
					objFormControlInfo.Text = this.txtDefaultText.Text;
					break;
					
				case Code5Systems.FormMaster.Business.ControlType.CheckBoxList:
				case Code5Systems.FormMaster.Business.ControlType.RadioButtonList:
					objFormControlInfo.RepeatDirection = int.Parse(this.lstRepeatDirection.SelectedValue).ToEnum<RepeatDirection>();
					objFormControlInfo.RepeatColumns = this.lstRepeatColumns.SelectedValue;
					break;
					
				case Code5Systems.FormMaster.Business.ControlType.TextBox:
					objFormControlInfo.Text = this.txtDefaultText.Text;
					objFormControlInfo.TextMode = int.Parse(this.lstTextMode.SelectedValue).ToEnum<TextBoxMode>();
					
					if (objFormControlInfo.TextMode == TextBoxMode.MultiLine)
					{
						if (this.txtRows.Text != string.Empty)
						{
							objFormControlInfo.Rows = this.txtRows.Text;
						}
					}
					
					objFormControlInfo.Columns = this.txtColumns.Text;
					
					objFormControlInfo.MaxLength = this.txtMaxLength.Text;
					objFormControlInfo.Placeholder = this.txtPlaceholder.Text;
					break;
					
				case Code5Systems.FormMaster.Business.ControlType.HiddenField:
					objFormControlInfo.Text = this.txtDefaultText.Text;
					break;
					
				case Code5Systems.FormMaster.Business.ControlType.ListBox:
					objFormControlInfo.SelectionMode = ListSelectionMode.Multiple;
					break;
					
				case Code5Systems.FormMaster.Business.ControlType.Label:
					objFormControlInfo.Text = htmlEditor.Text;
					objFormControlInfo.TabIndex = "-1";
					break;
					
				case Code5Systems.FormMaster.Business.ControlType.FileUpload:
					objFormControlInfo.MaxFileSize = int.Parse(this.txtMaxFileSize.Text);
					objFormControlInfo.StoreInDB = this.chkStoreInDB.Checked;
					objFormControlInfo.HideFileExtensions = this.chkHideFileExtensions.Checked;
					objFormControlInfo.HideMaxSize = this.chkHideMaxSize.Checked;
					objFormControlInfo.FileTypes = "";
					foreach (ListItem item in this.chkLstFileTypes.Items)
					{
						if (item.Selected)
						{
							objFormControlInfo.FileTypes += item.Value + ",";
						}
					}
					
					if (objFormControlInfo.FileTypes != string.Empty)
					{
						objFormControlInfo.FileTypes = objFormControlInfo.FileTypes.Substring(0, objFormControlInfo.FileTypes.Length - 1);
					}
					else
					{
						throw (new Exception(Localization.GetString("NoFileTypesSelected.Text", this.LocalResourceFile)));
					}
					break;
					
				case Code5Systems.FormMaster.Business.ControlType.SubmitButton:
					objFormControlInfo.ButtonType = int.Parse(this.lstButtonType.SelectedValue).ToEnum<Code5Systems.FormMaster.Business.ButtonType>();

					if (objFormControlInfo.ButtonType == Code5Systems.FormMaster.Business.ButtonType.ImageButton)
					{
						string[] aryFile = this.ctlImage.Url.Split('=');
						if (aryFile.Length == 2)
						{
							objFormControlInfo.ButtonImage = aryFile[1];
						}
					}
					break;
					
				case Code5Systems.FormMaster.Business.ControlType.HTMLEditor:
					if (string.IsNullOrEmpty(objFormControlInfo.Width))
					{
						objFormControlInfo.Width = "600";
					}
					if (string.IsNullOrEmpty(objFormControlInfo.Height))
					{
						objFormControlInfo.Height = "400";
					}
					break;
			}
		}
		
		private void TestQuery(string strQuery)
		{
			try
			{
				Code5Systems.FormMaster.Business.FormController objFormCtl = new Code5Systems.FormMaster.Business.FormController(ModuleId);
				DataTable dt = objFormCtl.GetQueryData(this.txtConnection.Text, strQuery);
				
				this.gvQueryResults.DataSource = dt;
				this.gvQueryResults.DataBind();
				this.gvQueryResults.Visible = true;
				this.trQueryResults.Visible = true;
				
				this.gvQueryResults.Visible = true;
				
			}
			catch (Exception ex)
			{
				DotNetNuke.UI.Skins.Skin.AddModuleMessage(_loaderCtl, ex.Message, DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError);
				this.trQueryResults.Visible = false;
			}
			
		}
		
		public List<ListItem> GetAvailableParentListControls(Code5Systems.FormMaster.Business.FormControlInfo thisCtrl)
		{
			List<ListItem> parents = new List<ListItem>();
			parents.Add(new ListItem(Localization.GetString("SelectParent", this.LocalResourceFile), "0"));
			for (int row = 0; row <= this.objFormInfo.CurrentPage.TableRows - 1; row++)
			{
				for (int col = 0; col <= this.objFormInfo.CurrentPage.TableColumns - 1; col++)
				{
					if (!tAry[row, col].IsEmpty)
					{
						if (tAry[row, col].FormControlInfo.Type == Code5Systems.FormMaster.Business.ControlType.DropDownList)
						{
							if (tAry[row, col].FormControlInfo.ID != thisCtrl.ID)
							{
								if ((!tAry[row, col].FormControlInfo.IsParentList) || (thisCtrl.ParentControlID == tAry[row, col].FormControlInfo.ID))
								{
									if (tAry[row, col].FormControlInfo.ParentControlID != thisCtrl.ID)
									{
										
										if (!ParentCandidatelInCascadeSet(thisCtrl, (string) (tAry[row, col].FormControlInfo.ID)))
										{
											parents.Add(new ListItem(tAry[row, col].FormControlInfo.FieldName, tAry[row, col].FormControlInfo.ID));
										}
										
									}
								}
							}
						}
						else
						{
							//Do Nothing
						}
					}
				}
			}
			return parents;
		}
		
		private bool ParentCandidatelInCascadeSet(Code5Systems.FormMaster.Business.FormControlInfo thisCtrl, string candidateID)
		{
			bool isInSet = false;
			Code5Systems.FormMaster.Business.FormControlInfo cascadeSetMember = thisCtrl;
			
			// Get to the top of the set if any
			while (cascadeSetMember.IsChildList)
			{
				cascadeSetMember = objFormCtl.GetFormControlInfo(cascadeSetMember.ParentControlID);
			}
			
			if (cascadeSetMember.IsParentList)
			{
				while (cascadeSetMember.ID != candidateID)
				{
					cascadeSetMember = objFormCtl.GetFormControlInfo(cascadeSetMember.ChildControlID);
					if (cascadeSetMember != null)
					{
						if (thisCtrl.ParentControlID != candidateID && cascadeSetMember.ID == candidateID)
						{
							isInSet = true;
							break;
						}
					}
					else
					{
						break;
					}
				}
			}
			
			return isInSet;
		}
		
		private Code5Systems.FormMaster.Business.FormPageInfo AddFormPage(int pageNum)
		{
			Code5Systems.FormMaster.Business.FormPageController pageCtlr = new Code5Systems.FormMaster.Business.FormPageController();
			Code5Systems.FormMaster.Business.FormPageInfo newPageInfo = new Code5Systems.FormMaster.Business.FormPageInfo()
			{
				FormID = objFormInfo.FormID,
				PageNum = pageNum,
				TableColumns = (byte) 1,
				TableRows = (byte) 1,
				LabelPosition = (byte) 1,
				ShortName = string.Format(Localization.GetString("FormPage", Utility.GetSharedResourceFile()), pageNum),
				PageData = Code5Systems.FormMaster.Business.Constants.DEFAULT_PAGE,
				CreatedByID = UserId,
				CreatedDate = DateTime.Now,
				LastModifiedByID = UserId,
				LastModifiedDate = DateTime.Now
			};
			
			newPageInfo.FormPageID = pageCtlr.AddFormPage(newPageInfo);
			objFormCtl.Pages.Add(newPageInfo);
			objFormCtl.VerifyPageNumbers();
			return newPageInfo;
		}
		
		private Code5Systems.FormMaster.Business.FormPageInfo CopyFormPage(int pageNum)
		{
			Code5Systems.FormMaster.Business.FormPageController pageCtlr = new Code5Systems.FormMaster.Business.FormPageController();
			List<Code5Systems.FormMaster.Business.FormControlInfo> cascadeCtls = new List<Code5Systems.FormMaster.Business.FormControlInfo>();
			Dictionary<string, string[]> cascadeMapping = new Dictionary<string, string[]>();
			
			Code5Systems.FormMaster.Business.FormPageInfo newPageInfo = new Code5Systems.FormMaster.Business.FormPageInfo()
			{
				FormID = objFormInfo.FormID,
				PageNum = pageNum,
				TableColumns = objFormInfo.CurrentPage.TableColumns,
				TableRows = objFormInfo.CurrentPage.TableRows,
				LabelPosition = objFormInfo.CurrentPage.LabelPosition,
				ShortName = string.Format(Localization.GetString("FormPageCopy", this.LocalResourceFile), objFormInfo.CurrentPage.ShortName),
				Title = string.Format(Localization.GetString("FormPageCopy", this.LocalResourceFile), objFormInfo.CurrentPage.Title),
				PageData = objFormInfo.CurrentPage.PageData,
				UseTitle = objFormInfo.CurrentPage.UseTitle,
				CreatedByID = UserId,
				CreatedDate = DateTime.Now,
				LastModifiedByID = UserId,
				LastModifiedDate = DateTime.Now
			};
			
			if (newPageInfo.ShortName.Length > 30)
			{
				newPageInfo.ShortName = newPageInfo.ShortName.Substring(0, 30);
			}
			if (newPageInfo.Title.Length > 250)
			{
				newPageInfo.Title = newPageInfo.Title.Substring(0, 250);
			}
			
			XDocument newPageDoc = XDocument.Parse(newPageInfo.PageData);
			
			Code5Systems.FormMaster.Business.CascadeMapper cascadeMap = new Code5Systems.FormMaster.Business.CascadeMapper();
			string origCtlID = default(string);
			Code5Systems.FormMaster.Business.FormControlInfo copiedCtrl = default(Code5Systems.FormMaster.Business.FormControlInfo);
			Code5Systems.FormMaster.Business.FormControlInfo cascadeCtrl;
			Code5Systems.FormMaster.Business.FormControlInfo copiedValidator = default(Code5Systems.FormMaster.Business.FormControlInfo);
			IEnumerable<XElement> xControls = from c in xDoc.Root.Elements("Controls").Elements("Control") select c;
			foreach (XElement xControl in xControls)
			{
				cascadeCtrl = null;
				copiedCtrl = objFormCtl.GetFormControlInfo(xControl);
				if (copiedCtrl != null)
				{
					origCtlID = copiedCtrl.ID;
					copiedCtrl.ID = "ctl_" + Guid.NewGuid().ToString().Replace("-", "");
					
					if (copiedCtrl.IsParentList || copiedCtrl.IsChildList)
					{
						cascadeMap.CascadeSet.Add(new Code5Systems.FormMaster.Business.CascadeInfo()
						{
							ID = copiedCtrl.ID,
							OldID = origCtlID,
							IsParent = copiedCtrl.IsParentList,
							IsChild = copiedCtrl.IsChildList,
							ParentID = copiedCtrl.ParentControlID,
							ChildID = copiedCtrl.ChildControlID
						});
					}
					
					copiedCtrl.FieldName = string.Format(Localization.GetString("FormPageCopy", this.LocalResourceFile).Replace(" ", ""), copiedCtrl.FieldName);
					foreach (Code5Systems.FormMaster.Business.FormControlInfo tempLoopVar_copiedValidator in copiedCtrl.Validators)
					{
						copiedValidator = tempLoopVar_copiedValidator;
						switch (copiedValidator.Type)
						{
							case Code5Systems.FormMaster.Business.ControlType.ChkListValidator:
								copiedValidator.ID = "clv_" + Guid.NewGuid().ToString().Replace("-", "");
								break;
							case Code5Systems.FormMaster.Business.ControlType.CompareValidator:
								copiedValidator.ID = "cv_" + Guid.NewGuid().ToString().Replace("-", "");
								break;
							case Code5Systems.FormMaster.Business.ControlType.RegularExpressionValidator:
								copiedValidator.ID = "rev_" + Guid.NewGuid().ToString().Replace("-", "");
								break;
							case Code5Systems.FormMaster.Business.ControlType.RequiredFieldValidator:
								copiedValidator.ID = "rfv_" + Guid.NewGuid().ToString().Replace("-", "");
								break;
								
						}
						copiedValidator.ControlToValidate = copiedCtrl.ID;
					}
					objFormCtl.UpdateControlValues(newPageDoc, copiedCtrl);
					//newPageInfo.PageData = newPageDoc.ToString()
				}
			}
			
			newPageInfo.PageData = newPageDoc.ToString();
			
			if (cascadeMap.CascadeSet.Count > 0)
			{
				string newControlID = string.Empty;
				Code5Systems.FormMaster.Business.FormControlInfo newControl = default(Code5Systems.FormMaster.Business.FormControlInfo);
				System.Collections.Generic.List<Code5Systems.FormMaster.Business.FormControlInfo> newControls = objFormCtl.GetFormControlArray(newPageInfo);
				Code5Systems.FormMaster.Business.CascadeInfo newParent = default(Code5Systems.FormMaster.Business.CascadeInfo);
				Code5Systems.FormMaster.Business.CascadeInfo newChild = default(Code5Systems.FormMaster.Business.CascadeInfo);
				foreach (Code5Systems.FormMaster.Business.CascadeInfo casInfo in cascadeMap.CascadeSet)
				{
					newControlID = casInfo.ID;
					newControl = newControls.Where(c => c.ID == newControlID).SingleOrDefault();
					if (newControl != null)
					{
						newParent = cascadeMap.CascadeSet.Where(c => c.OldID == newControl.ParentControlID).SingleOrDefault();
						if (newParent != null)
						{
							newControl.ParentControlID = newParent.ID;
						}
						newChild = cascadeMap.CascadeSet.Where(c => c.OldID == newControl.ChildControlID).SingleOrDefault();
						if (newChild != null)
						{
							newControl.ChildControlID = newChild.ID;
						}
						objFormCtl.UpdateControlValues(newPageDoc, newControl);
					}
				}
			}
			
			newPageInfo.PageData = newPageDoc.ToString();
			newPageInfo.FormPageID = pageCtlr.AddFormPage(newPageInfo);
			objFormCtl.Pages.Add(newPageInfo);
			objFormCtl.VerifyPageNumbers();
			
			return newPageInfo;
		}
		
		private Code5Systems.FormMaster.Business.FormPageInfo GetCurrentPage()
		{
			int.TryParse(this.currentPage.Value, out _curPage);
			return objFormCtl.Pages.Find(p => p.PageNum == _curPage);
		}
#endregion
		
	}
}

